package bit_operation;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description int -> ipv4
 * @Author Firenut
 * @Date 2023-08-24 20:02
 */
public class IntToIPV4 {
    public static void main(String[] args) {
        System.out.println(intToIPV4(167773121));
        System.out.println(intToIp(167773121));
    }

    static String intToIPV4(int num) {
        StringBuilder sb = new StringBuilder();
        List<Integer> ans = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            ans.add(num & 255);
            num >>= 8;
        }

        for (int i = ans.size() - 1; i >= 0; i--) {
            sb.append(ans.get(i));
            if (i != 0) {
                sb.append(".");
            }
        }
        return sb.toString();
    }

    public static String intToIp(int ipInt) {
        // 将32位整数分割为四个8位的部分
        int part1 = (ipInt >> 24) & 255;
        int part2 = (ipInt >> 16) & 255;
        int part3 = (ipInt >> 8) & 255;
        int part4 = ipInt & 255;
        // 构建 IPv4 地址字符串
        return part1 + "." + part2 + "." + part3 + "." + part4;
    }
}
